# -*- coding: utf-8 -*-
import json
from datetime import datetime

import requests
from django.conf import settings

from common.platform.common.model import PLATFORM_TYPE
from common.utils import track_logging
from common.utils import tz

_LOGGER = track_logging.getLogger(__name__)

ES_TRANS_HOST = settings.ES_HOST + '/' + 'gameorders'

req_session = requests.Session()


def emit_game_order(user_id, platform_type, game_id, order_id, bet_amount, bet_result, created_at):
    assert user_id > 0
    assert platform_type in PLATFORM_TYPE.values()
    assert isinstance(game_id, (int, long))
    assert isinstance(order_id, (int, long))
    assert isinstance(bet_amount, (int, long))
    assert isinstance(bet_result, (int, long))
    assert isinstance(created_at, datetime)

    doc_id = '{}_{}_{}'.format(platform_type, game_id, order_id)

    op_url = '{es_host}/_doc/{doc_id}'.format(es_host=ES_TRANS_HOST, doc_id=doc_id)
    response = req_session.put(op_url, data=json.dumps({
        'user_id': user_id,
        'platform_type': platform_type,
        'game_id': game_id,
        'order_id': order_id,
        'bet_amount': bet_amount,
        'bet_result': bet_result,
        'created_at': tz.to_ts(created_at),
    }), headers={'Content-Type': 'application/json'})
    _LOGGER.info('response: %s' % response.content)
    if response.status_code not in [200, 201]:
        raise Exception('emit game order error')


def query_game_orders(user_id=None, platform_type=None, game_id=None, order_id=None, start_created_at=None,
                end_created_at=None, page=1, page_size=10, order_by=None):
    """
    the method return:
    {
        "total": 120,
        "orders": [
        ]
    }
    """
    criteria = {
        "query": {
            "bool": {
                "filter": []
            }
        },
        "from": (page - 1) * page_size,
        "size": page_size,
        "sort": [{"created_at": "desc"}]
    }
    _filter = criteria['query']['bool']['filter']
    if user_id:
        _filter.append({'term': {'user_id': user_id}})
    if platform_type:
        _filter.append({'term': {'platform_type': platform_type}})
    if game_id:
        _filter.append({'term': {'game_id': game_id}})
    if order_id:
        _filter.append({'term': {'order_id': order_id}})
    if start_created_at or end_created_at:
        created_at_range = dict()
        if start_created_at:
            created_at_range['gte'] = start_created_at
        if end_created_at:
            created_at_range['lt'] = end_created_at
        _filter.append({'range': {"created_at": created_at_range}})

    # if order_by:
    # criteria['sort']

    op_url = '{es_host}/_doc/_search'.format(es_host=ES_TRANS_HOST)
    _LOGGER.info('search criteria: %s' % json.dumps(criteria))
    response = requests.post(op_url, data=json.dumps(criteria), headers={'Content-Type': 'application/json'})
    _LOGGER.info('search response: %s' % response.content)
    if response.status_code != 200:
        raise Exception('search error')
    resp_json = json.loads(response.content)
    if 'hits' not in resp_json:
        raise Exception('search error')

    result = {
        'total': resp_json['hits']['total'],
        'orders': [i['_source'] for i in resp_json['hits']['hits']]
    }

    return result
